var SDKAPPID = 1400039219;
var PREFIX = 'zhuawawa_' + SDKAPPID;
var ACCOUNTTYPE = 14418;
var BIZID = 8525;
var SVRDOMAIN = "https://sxb.qcloud.com/sxb_dev/";
// 这是业务域名
var CATCHER_DOMAIN = "https://yun.tim.qq.com/v4/ilvb_doll_catch/";

var reportSto = null;
var AppInfo = {
  loginInfo : {
    identifier: null,
    token: null,
    userSig: null
  }
};

var query = {
  get: function (n) {
    var m = window.location.search.match(new RegExp("(\\?|&)" + n + "=([^&]*)(&|$)"));
    return !m ? "" : decodeURIComponent(m[2]);
  }
};
var Detector = {
  Android: function () {
    return /Android/i.test(navigator.userAgent);
  },
  iOS: function () {
    return /iPhone|iPad|iPod/i.test(navigator.userAgent);
  },
  safari: function () {
    return navigator.userAgent.toLowerCase().indexOf('safari/') > -1 && navigator.userAgent.toLowerCase().indexOf('chrome/') === -1;
  }
};
var AppSvr = {
  setErrorHandler: function (cb) {
    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
      // Do something with response data
      // console.debug('axios',response);
      if (cb) {
        cb(response);
      }
      return response;
    }, function (error) {
      // Do something with response error
      return Promise.reject(error);
    });
  },
  login: function (opts, succ, err) {
    axios.post(SVRDOMAIN + '?svc=doll&cmd=fetchsig', JSON.stringify({
      "id": opts.username,
      "appid": SDKAPPID
    }))
      .then(function (response) {
        if (response.status == 200) {
          succ(response.data);
        } else {
          err(response.data);
        }
      })
      .catch(function (error) {
        err(error);
      });
  },


  getRoomList: function (succ, err) {
    axios.get(SVRDOMAIN + '?svc=doll&cmd=roomlist')
      .then(function (response) {
        if (response.status == 200) {
          succ(response.data);
        } else {
          err(response.data);
        }
      })
      .catch(function (error) {
        err(error);
      });
  },



  buildUrl: function (name ,domain) {
    var urlParams = {
      sdkappid: SDKAPPID,
      usersig: AppInfo.loginInfo.userSig,
      identifier: AppInfo.loginInfo.identifier,
      random: parseInt(Math.random(0, 1) * 100000000),
      contenttype: 'json'
    };
    var str = ""
    for (var key in urlParams) {
      if (str != "") {
        str += "&";
      }
      str += key + "=" + encodeURIComponent(urlParams[key]);
    }

    return (domain ? domain : CATCHER_DOMAIN) + name + "?" + str;
  },

  applyWsUrl: function (succ, err) {
    axios.post(this.buildUrl('room_addr'), JSON.stringify({
      "GroupId": parseInt(app.roomnum)
    }))
      .then(function (response) {
        if (response.status == 200) {
          succ(response.data);
        } else {
          err(response.data);
        }
      })
      .catch(function (error) {
        err(error);
      });
  }
};


Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus the element
    el.focus()
  }
})


var renderUserListItv = null;
var remainTimeSto = null;
var app = new Vue({
  el: '#app-main',
  data: {
    form: {
      msg: null,
      username: null
    },
    logined: false,
    view: 1,
    roomList: [],
    roomnum:  null,
    roomInfo:null,
    loginInfo: null,
    joinRoomModal: false,
    createRoomModal: false,
    video_list: [],
    configRole: "user",
    websocket: null,
    catcher: {
      state: 0,
      waitNumber: 0,
      remain_time: 60,
      move: null
    },
    player: null,
    lvburl: null,
    nipple: null,
    alreadySendQueueRequest: 0,
    rtcPlayer: null,
    front: true,
    isReady: false, //是否准备好了
    pressed: {
      start: false,
      left: false,
      up: false,
      right: false,
      down: false,
      catcher: false,
      togger: false,
      restart: false
    },

    Directive: {
      CTL_LEFT_START: "left",
      CTL_LEFT_END: "left_end",
      CTL_RIGHT_START: "right",
      CTL_RIGHT_END: "right_end",
      CTL_FORWARD_START: "up",
      CTL_FORWARD_END: "up_end",
      CTL_BACKWARD_START: "down",
      CTL_BACKWARD_END: "down_end",
      CTL_CATCH: "catch",
      CTL_STOP: "stop"
    },

    gameResult: 0 // -1 未中奖， 0 准备中，游戏中  1 中奖了
  },
  components: {
    'vue-toastr': window.vueToastr
  },
  filters: {
  },
  watch: {
    front(val) {
      var mainCanvas = document.getElementById("main_camera");
      var sideCanvas = document.getElementById("side_camera");
      if(val){
        TXWawaVideo.renderFront();
        mainCanvas.style.display = 'block'
        sideCanvas.style.display = 'none'
        // TXWawaVideo.renderFront([mainCanvas,sideCanvas]);
      } else {
        TXWawaVideo.renderSide();
        mainCanvas.style.display = 'none'
        sideCanvas.style.display = 'block'
      }
      
    },
    view(val) {
      var self = this;
      if (val == 2) {
        this.isReady = false;
      } else if (val == 3) {
        this.lvburl = '';
      }
    }
  },

  mounted() {
    var self = this
    AppSvr.setErrorHandler(function (response) {
      var data = response.data;
      var errorCode = typeof data.ErrorCode !== 'undefined' ? data.ErrorCode : data.errorCode
      switch (errorCode) {
        case 0:
        case 10003:
          break;
        case 10009:
          self.$root.$refs.toastr.w("登录态失效");
          self.logout();
          break;
        default:
          self.$root.$refs.toastr.w(data.errorInfo || data.ErrorInfo);
          break;
      }
    });

    //生成一个随机账号登录
    this.form = {
      username: "catcher-" + parseInt(Math.random(0, 1) * 1000000000000)
    };
    self.login();
  },

  computed: {
    showWin() {
      return this.gameResult === 1;
    },
    showLose() {
      return this.gameResult === -1;
    },
    remainTime() {
      return this.catcher.state == 1 && this.catcher.remain_time * 1 > 0 ? this.catcher.remain_time + "秒" : "";
    }
  },

  methods: {
    doSwitcher: function () {
      this.front = !this.front
    },
    restoreVideo: function () {
      var self = this;
      setTimeout(function () {
        Array.prototype.forEach.call(self.video_list, function (item, idx) {
          var video = document.getElementById(item.videoId)
          if (!video) return
          if (self.isSafari) {
            //safari 的特殊处理逻辑
            if (item.stream && item.stream.getVideoTracks().length != 0 && video && video.srcObject && video.srcObject.active === false) {

              var videoMedia = new MediaStream();
              videoMedia.addTrack(item.stream.getVideoTracks()[0]);
              video.srcObject = videoMedia;
            }
            var audio = document.getElementById(item.videoId + '_audio')
            if (!audio) return
            if (item.stream && item.stream.getAudioTracks().length != 0 && audio && audio.srcObject && audio.srcObject.active === false) {
              var audioMedia = new MediaStream();
              audioMedia.addTrack(item.stream.getAudioTracks()[0]);
              audio.srcObject = audioMedia;
            }
          } else {
            if (item.stream && video && video.srcObject && video.srcObject.active === false) {
              video.srcObject = item.stream;
            }
          }
        })
      }, 100);
    },
    login: function (e) {
      var self = this;
      if (this.form.username) {
        store.set(PREFIX + "username", this.form.username);
      }
      AppSvr.login(this.form, function (data) {
        if (data && data.errorCode === 0) {
          AppInfo.loginInfo.identifier = self.form.username;
          AppInfo.loginInfo.token = data.data.token;
          AppInfo.loginInfo.userSig = data.data.userSig;
          store.set(PREFIX + "loginInfo", AppInfo.loginInfo);
          self.loginInfo = AppInfo.loginInfo;
          // self.$root.$refs.toastr.s("登录成功");
          //展示房间列表
          self.renderRoomList();
        } else {
          console.error(data)
          alert("获取UserSig失败, Info = " + JSON.stringify(data));
        }
      }, function (error) {
        console.error(error)
      });
    },

    logout: function () {
      store.remove(PREFIX + "loginInfo");
      this.view = 0;
    },

    goReady: function () {
      this.isReady = true;
      if (this.player) {
        try {
          this.player.play()
        } catch (e) {
          console.error(e)
        }
      }
    },

    renderRoomList: function () {
      var self = this
      AppSvr.getRoomList(function (data) {
        console.debug(data);
        self.roomList = data.data;
      });
    },

    chooseRoom: function (roomInfo) {
      this.roomnum = roomInfo.id;
      this.roomInfo = roomInfo;
      this.getLiveUrl();
    },

    joinRoom: function () {
      if (!this.roomnum) {
        this.$root.$refs.toastr.w('请先选择房间');
        return
      }
      this.createRoom();
    },

    catcherHandlerWait: function (data) {
      var self = this
      if (typeof data === 'undefined' || data < 0) {
        console.error('异常处理')
        return;
      }
      self.catcher.waitNumber = data;
      if (data > 0) {
        this.$root.$refs.toastr.s("排队中，请稍候");
        console.debug('排队中')
      } else if (data == 0) {
        console.debug('开始游戏')
      }
    },
    //准备好了，一定要在准备好以后，再开始游戏
    //开始游戏可以认为是一个投币的行为
    catcherHandlerReady: function (data) {
      this.renderPlay();
    },
    catcherHandlerResult: function (data) {
      var self = this
      console.debug('catcherHandlerResult', data)
      if (data === false) {
        this.gameResult = -1;
        // self.$root.$refs.toastr.w(`没有抽中，再接再厉`);
      } else {
        //self.$root.$refs.toastr.s(`抽中了！！！`);
        this.gameResult = 1;
      }

      //ios在抽中以后，一定要离开房间，释放控制端和视频端
      TXWawaPlayer.quitGame();
      setTimeout(function () {
        self.quitRoom();
      }, 2000)
    },
    catcherHandlerState: function (data) {
      //看这里看这里看这里
      // https://gitee.com/vqcloud/wawaji_H5
      // 等待中	TXWawaPlayer.MachineState.WAIT
      // 游戏中	TXWawaPlayer.MachineState.PLAY
      // 抓取中	TXWawaPlayer.MachineState.CATCH
      // 娃娃机的状态异常	TXWawaPlayer.MachineState.ERROR
      var self = this;
      self.catcher.state = data;
    },
    catcherHandlerTime: function (data) {
      this.catcher.remain_time = data
    },
    //切换摄像头
    toggleView: function () {
      this.front = !this.front;
    },
    catcherDoMove: function (dir) {
      TXWawaPlayer.controlClaw(dir)
    },
    getLiveUrl: function () {
      var param = [this.roomnum, this.roomInfo.front, "main"]
      console.debug( this.roomnum, this.roomInfo.front, "main" );
      var cryto = md5(param.join("_"))
      this.lvburl = window.location.protocol + `//${BIZID}.liveplay.myqcloud.com/live/${BIZID}_${cryto}.m3u8`
      console.debug('rtmp url',this.lvburl);
      // if (this.player) {
      //   this.playerDestroy();
      //   this.$refs.lvb.innerHTML = ''
      // }
      //this.lvburl = 'https://8525.liveplay.myqcloud.com/live/8525_e3b0de451fd817c8333d20cd2717172a.m3u8';
      // return
      // this.player = new TcPlayer('lvb', {
      //   "m3u8": this.lvburl,
      //   "autoplay": true,      //iOS下safari浏览器是不开放这个能力的
      //   "width": "100%",
      //   "height": "100vh",
      //   "wording": {
      //     2032: "请求视频失败，请检查网络",
      //     2048: "请求m3u8文件失败，可能是网络错误或者跨域问题"
      //   }
      // });
    },

    //观看
    renderWatch: function () {
      var self = this
      this.view = 2
      this.createRoomModal = false
      this.joinRoomModal = false
      if (this.$refs.lvb_video) {
        this.$refs.lvb_video.play();
      }
      this.getLiveUrl();
    },

    //开始排队
    //这里应该向你的业务svr请求
    //业务svr进行权限判断/扣费逻辑完成后，返回ws地址
    //然后进行ws的排队
    startQueue: function () {
      var self = this
      if (this.alreadySendQueueRequest) return
      this.alreadySendQueueRequest = 1;
      AppSvr.applyWsUrl(function (data) {
        // 生成唯一的ID , 作为游戏id
        var playId = Date.now().toString(32) + Math.random().toString(32).split('.')[1];
        TXWawaPlayer.startQueue(playId, data.WsUrl);

      }, function (err) {
        console.error(err);
        self.alreadySendQueueRequest = 0;
      });
    },

    
    getSig: function(succ , err){
      axios.get('https://sxb.qcloud.com/wawaji_svr/tea.php?act=genSig'
      +'&sdkappid=' + SDKAPPID
      +'&ver=2'
      +'&groupid='+this.roomnum
      +'&expired=3000'
    )
      .then(function (response) {
        if (response.status == 200) {
          succ(response.data);
        } else {
          err(response.data);
        }
      })
      .catch(function (error) {
        err(error);
      });
    },

    //这是获取视频流加密串的接口
    //特别注意
    //这里是为了让业务侧的视频流被真正的用户按需拉取，而不是被“坏人”通过拼接地址就能直接请求
    //视频资源稀缺且珍贵
    //这个接口应该由业务方（也就是看代码的你）来实现，
    //具体的实现方式请参考文档
    getSig: function(succ , err){
      axios.get('https://sxb.qcloud.com/wawaji_svr/tea.php?act=genSig'
      +'&sdkappid=' + SDKAPPID
      +'&ver=2'
      +'&groupid='+this.roomnum
      +'&expired=3000'
    )
      .then(function (response) {
        if (response.status == 200) {
          succ(response.data);
        } else {
          err(response.data);
        }
      })
      .catch(function (error) {
        err(error);
      });
    },

    renderPlayVideo: function () {
      var mainCanvas =  document.getElementById("main_camera");
      var self = this
      //再次提醒
      //获取的加密串有效期是从拉取接口开始计算的，而不是从视频拉取开始计算的
      //要理解这里的差异
      this.getSig(function(json){
        TXWawaVideo.init({
          sdkappid: SDKAPPID,
          accounttype: 13001,
          roomId: self.roomnum,
          identifier: AppInfo.loginInfo.identifier,
          usersig: AppInfo.loginInfo.userSig, 
          front: self.roomInfo.front,
          side: self.roomInfo.side,
          ver:2,
          sig:json.sig,
          // renderType:0,
          listeners: {
            errorNotify: this.errorNotify,
            infoNotify: this.infoNotify
          }
        }, function (res) {
          //这里负责渲染视频
          var mainCanvas = document.getElementById("main_camera");
          var sideCanvas = document.getElementById("side_camera");
          TXWawaVideo.renderVideo([mainCanvas,sideCanvas] , function(){
            console.debug('视频渲染开始')
            TXWawaPlayer.startGame();
          });
        }, function (err) {
          console.debug(err)
        })
      }, function(err){
          console.error('gen sig failed',err)
      })
    },

    /* 
    errorNotify 会抛下面这些异常，部分是开发阶段需要注意的，部分是需要由业务处理的
    |4000    | sdkappid not in white list | 不在白名单中 |
    |4001 | kick out  | 只支持用户拉取，被其他请求抢占，被T掉 |
    |4010 | signature timeout | 时间戳超时 |
    |4011 | Sigature Decrypt Error | 解密错误 |
    |4012 | URL parameter error | URL参数错误 |
    |4013 | Signature not exist | 签名长度错误 |
    |4020 | room not exist | 未创建房间 |
    |4021 | user info not exist | 用户信息不存在 |
    */
    errorNotify: function(ev){
      console.error(ev)
    },
    infoNotify: function(){

    },
    renderPlay: function () {
      this.view = 3;
      this.createRoomModal = false;
      this.joinRoomModal = false;
      var self = this


      setTimeout(function () {
        self.renderPlayVideo();
        
        // mainCanvas.setAttribute('style', style);
      }, 100);

      // this.catcherDoStartGame();

      if (this.player) {
        this.playerDestroy();
      }
    },

    createRoom: function () {
      var self = this;
      this.entryType = 'create';
      TXWawaPlayer.init({
        OnWait: self.catcherHandlerWait,
        OnReady: self.catcherHandlerReady,
        OnState: self.catcherHandlerState,
        OnCoin: self.catcherHandlerCoin,
        OnResult: self.catcherHandlerResult,
        OnDelay: self.catcherHandlerDelay,
        OnTime: self.catcherHandlerTime,
        OnClose: function (info) {
          console.warn(info);
        },
        OnError: function (error) {
          console.error(error);
          if (error.code === TXWawaPlayer.ErrorCode.WebSocketError.code) {
            self.$root.$refs.toastr.e(error.msg)
            TXWawaPlayer.quitGame();
            setTimeout(function () {
              self.quitRoom();
            }, 2000)
          }
        }
      })
      if (query.get("dev")) {
        this.renderPlay();
      } else {
        this.renderWatch();
      }

    },
    quitRoom: function () {

      if (query.get("dev")) {
        return
      }

      var self = this;
      this.view = 2;
      this.alreadySendQueueRequest = 0;
      this.video_list = [];
      TXWawaPlayer.quitGame();
      TXWawaPlayer.destroy();

      location.reload();
    },


    onJoinRoomCallback: function (result) {
      var self = this;
      if (result !== 0) {
        self.$root.$refs.toastr.e("create room failed!!!");
        return;
      }
    },

    calcMaxDragRange: function () {
      // $('.sub-video') 有个90度旋转 所以高度和宽度互调
      var topEl = $('.control');
      return [topEl.outerHeight() + parseInt(topEl.css('top')),
      $(window).width() - $('.sub-video').outerHeight() - 20 - 20,
      $(window).height() - $('.nipple-wrapper').outerHeight() - (topEl.outerHeight() + parseInt(topEl.css('top'))) - $('.sub-video').outerWidth() / 2,
        0];
    },

    initDrag: function () {
      this.$nextTick(function () {
        var range = this.calcMaxDragRange();
        console.log(range);
        $('.sub-video').pep({
          useCSSTranslation: false,
          constrainTo: range
        });
      });
    },


    // 抓娃娃
    catcherDoCatch: function(){
      TXWawaPlayer.controlClaw( this.Directive.CTL_CATCH );
    },
    //操控
    touch(dir) {
      if (!this.front) { // 摄像头反过来了，需要处理映射关系
        switch (dir) {
          case this.Directive.CTL_LEFT_START:
            dir = this.Directive.CTL_BACKWARD_START;
            break;
          case this.Directive.CTL_LEFT_END:
            dir = this.Directive.CTL_BACKWARD_END;
            break;

          case this.Directive.CTL_RIGHT_START:
            dir = this.Directive.CTL_FORWARD_START;
            break;
          case this.Directive.CTL_RIGHT_END:
            dir = this.Directive.CTL_FORWARD_END;
            break;

          case this.Directive.CTL_FORWARD_START:
            dir = this.Directive.CTL_LEFT_START;
            break;
          case this.Directive.CTL_FORWARD_END:
            dir = this.Directive.CTL_LEFT_END;
            break;

          case this.Directive.CTL_BACKWARD_START:
            dir = this.Directive.CTL_RIGHT_START;
            break;
          case this.Directive.CTL_BACKWARD_END:
            dir = this.Directive.CTL_RIGHT_END;
            break;

          case this.Directive.CTL_CATCH:
            dir = this.Directive.CTL_CATCH;
            break;
          case this.Directive.CTL_STOP:
            dir = this.Directive.CTL_STOP;
            break;
        }
      }
      TXWawaPlayer.controlClaw(dir);
    },

    hideResultPanel() {
      this.gameResult = 0;
    }
  }
})
